﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vds2465Telegrams;

namespace Vds2465Parser
{
	internal static class GenParse_UserData_Report
	{
		#region internal methods

		internal static byte[] GenerateBytes(UserData userData, int nrOfBytes, byte userDataTypeByte)
		{
			byte[] userDataBytes = null;

			if (userData is UserData_Report)
			{
				UserData_Report userDataReport = userData as UserData_Report;
				userDataBytes = new byte[nrOfBytes];
				userDataBytes[0] = (byte) (nrOfBytes - GenParse_UserData.HeaderLength);	// user data length
                userDataBytes[1] = userDataTypeByte;
				userDataBytes[2] = userDataReport.Device;
				userDataBytes[3] = userDataReport.Address;
				userDataBytes[4] = userDataReport.AddressAddOn;
                userDataBytes[5] = GenParse_AddressExtension.GenerateByte_AddExt_1(userDataReport.AddressExtension);
				userDataBytes[6] = GenParse_ReportType.GenerateByte(userDataReport.TheReportType);
			}
			else
			{
				// TODO handle error
			}

			return userDataBytes;
		}

		internal static bool ParseBytes(byte[] userDataBytes, int expectedNrOfBytes, int expectedUserDataTypeByte, 
								out byte device, out byte address, out byte addressAddOn, out eAddressExtension_1 addressExtension, out ReportType_Base reportTypeBase)
		{
			// set default values
			device = 0x00;
			address = 0x00;
			addressAddOn = 0x00;
			addressExtension = 0x00;
			reportTypeBase = null;

			if (userDataBytes.Length >= expectedNrOfBytes)
			{
				// first byte
				if (userDataBytes[0] == expectedNrOfBytes - GenParse_UserData.HeaderLength)
				{
                    if (userDataBytes[1] == expectedUserDataTypeByte)
					{
						device = userDataBytes[2];
						address = userDataBytes[3];
						addressAddOn = userDataBytes[4];
                        bool bRetVal = GenParse_AddressExtension.ParseByte_AddExt_1(userDataBytes[5], out addressExtension);
						if (bRetVal)
						{
							return GenParse_ReportType.ParseByte(userDataBytes[6], out reportTypeBase);
						}

						// TODO handle error - parsing of address extension has failed
						return false;
					}

					// TODO handle error - wrong value for the data type
					return false;
				}

				// TODO handle error (wrong value in first byte the length)
				return false;
			}

			// TODO handle error (not enough bytes)
			return false;
		}

		#endregion internal methods
	}
}
